import React, { useEffect, useState, useRef } from 'react';
import { message, Row, Col } from 'antd';
import ProForm, { ProFormCaptcha, ProFormText, ModalForm } from '@ant-design/pro-form';
import { history, useModel } from 'umi';
import Footer from '@/components/Footer';
import styles from './index.less';
import { setToken } from '@/utils/utils';
import { LockTwoTone, UserOutlined, SafetyOutlined, GlobalOutlined } from '@ant-design/icons';
import type { ImageCodeType } from '@/services/login';
import { getImageCode, login, getMessageCode, forgetLoginKey } from '@/services/login';
import { queryCurrent } from '@/services/user';
import type { FormInstance } from 'antd/lib/form';
import Setting from '../../../../config/defaultSettings';

/**
 * 此方法会跳转到 redirect 参数所在的位置
 */
const goto = () => {
  if (!history) return;
  setTimeout(() => {
    const { query } = history.location;
    const { redirect } = query as { redirect: string };
    history.replace(redirect || '/');
  }, 10);
  history.replace('/');
};

const Login: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [imageInfo, setImageInfo] = useState<ImageCodeType>({
    imageCodeKey: '',
    imageCodeBase64: '',
  });
  const [imageForgetPswInfo, setImageForgetPswInfo] = useState<ImageCodeType>({
    imageCodeKey: '',
    imageCodeBase64: '',
  });
  const [modalVisible, setModalVisible] = useState(false);
  const loginRef = useRef<FormInstance>(); // 操作修改表单
  const updateRef = useRef<FormInstance>(); // 操作修改表单

  const fetchUserInfo = async () => {
    const data = await queryCurrent();
    if (data) {
      setInitialState({
        ...initialState,
        currentUser: {
          name: data,
          avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
          isSuper: false,
        },
      });
    }
  };

  /**
   *
   * @param type 类型 1登录|2忘记密码
   */
  const getImageInfo = async (type: 1 | 2) => {
    const data = await getImageCode();
    if (type === 1) {
      setImageInfo(data);
    } else {
      updateRef.current?.setFieldsValue({
        imageCodeKey: data.imageCodeKey,
      });
      setImageForgetPswInfo(data);
    }
  };

  useEffect(() => {
    getImageInfo(1);
  }, []);

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div>
          <GlobalOutlined className={styles.networkIcon} />
        </div>
        <div className={styles.main}>
          <ProForm
            className={styles.proForm}
            submitter={{
              searchConfig: {
                submitText: '登录',
              },
              render: (_, dom) => dom.pop(),
              submitButtonProps: {
                size: 'large',
                style: {
                  width: '100%',
                },
              },
            }}
            validateTrigger="onBlur"
            formRef={loginRef}
            onFinish={async (values) => {
              const params = {
                phone: values.phone,
                password: values.password,
                imageCode: values.imageCode,
                imageCodeKey: imageInfo?.imageCodeKey || '',
              };
              const data = await login(params);
              if (data != null) {
                const { name, token, reasonId } = data;
                if (name) {
                  setToken(token);
                  await fetchUserInfo();
                  goto();
                } else {
                  getImageInfo(1);
                  message.error(reasonId === 1 ? '不存在的账号' : '登录名密码错误');
                }
              } else {
                loginRef.current?.resetFields(['imageCode']);
                getImageInfo(1);
              }
            }}
          >
            <>
              <h1
                style={{
                  textAlign: 'center',
                  marginBottom: 10,
                  marginTop: '80px',
                }}
              >
                <img
                  style={{
                    height: '44px',
                    marginRight: 16,
                  }}
                  alt="logo"
                  // TODO 换logo
                  // src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg"
                  src="../logo.svg"
                />
                <span className={styles.Title}>{Setting.title}</span>
              </h1>
              <h5 className={styles.smallTitle}>
                Yunnan easy to use software Co., Ltd., Internet information service.
              </h5>
              <Row
                style={{
                  borderBottom: '1px solid rgba(0, 0, 0, 0.06)',
                  width: '360px',
                  paddingBottom: '15px',
                  marginBottom: '25px',
                }}
              >
                <Col>
                  <span
                    style={{
                      fontFamily: 'OPPOSans',
                      fontWeight: 'bolder',
                      fontStyle: 'Medium',
                      fontSize: '16px',
                    }}
                  >
                    登录
                  </span>
                </Col>
              </Row>

              <ProFormText
                name="phone"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder="请输手机号"
                rules={[
                  {
                    required: true,
                    message: '请输入手机号',
                  },
                  {
                    pattern: /^1[3-9][0-9]{9}$/,
                    message: '手机号格式错误！！！',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockTwoTone className={styles.prefixIcon} />,
                }}
                placeholder="请输入用户密码！"
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                  {
                    pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,
                    message: '密码格式错误！！！',
                  },
                ]}
              />
              <Row>
                <Col span={15}>
                  <ProFormText
                    name="imageCode"
                    fieldProps={{
                      size: 'large',
                      prefix: <SafetyOutlined className={styles.prefixIcon} />,
                    }}
                    rules={[
                      {
                        required: true,
                        message: '请输入图片验证码！',
                      },
                      {
                        pattern: /^[\s\S]{4}$/,
                        message: '验证码输入错误',
                      },
                    ]}
                    placeholder="请输入图片验证码"
                  />
                </Col>
                <Col span={9} style={{ textAlign: 'right' }}>
                  <img
                    src={imageInfo?.imageCodeBase64}
                    className={styles.loginImage}
                    onClick={() => getImageInfo(1)}
                  />
                </Col>
              </Row>
            </>
            <a
              style={{
                float: 'right',
                marginBottom: '16px',
              }}
              onClick={() => {
                getImageInfo(2);
                setModalVisible(true);
              }}
            >
              忘记密码
            </a>
          </ProForm>
        </div>
      </div>

      {/* 忘记密码 */}
      <ModalForm
        title="忘记密码"
        formRef={updateRef}
        visible={modalVisible}
        layout="horizontal"
        labelAlign="right"
        labelCol={{ span: 5 }}
        width={600}
        modalProps={{
          onCancel: () => {
            setModalVisible(false);
          },
        }}
        onFinish={async (values) => {
          const params = {
            phone: values.phone,
            messageCode: values.messageCode,
            newLoginKey: values.loginKey,
          };
          const data = await forgetLoginKey(params);
          if (data) {
            setModalVisible(false);
            message.success('修改成功!');
          } else {
            updateRef.current?.resetFields(['imageCode']);
            getImageInfo(2);
          }
        }}
      >
        <div
          style={{
            width: 330,
            margin: 'auto',
          }}
        >
          <ProFormText
            fieldProps={{
              size: 'large',
            }}
            name="phone"
            placeholder="请输入手机号"
            rules={[
              {
                required: true,
                message: '请输入手机号!',
              },
              {
                pattern: /^1\d{10}$/,
                message: '不合法的手机号格式!',
              },
            ]}
          />
          <Row>
            <Col span={15}>
              <ProFormText
                name="imageCode"
                fieldProps={{
                  size: 'large',
                }}
                placeholder="请输入图片验证码"
                rules={[
                  {
                    required: true,
                    message: '请输入图片验证码',
                  },
                ]}
              />
            </Col>
            <Col span={9} style={{ textAlign: 'right' }}>
              <img
                src={imageForgetPswInfo?.imageCodeBase64}
                className={styles.loginImage}
                onClick={() => getImageInfo(2)}
              />
            </Col>
          </Row>
          <ProFormCaptcha
            fieldProps={{
              size: 'large',
            }}
            captchaProps={{
              size: 'large',
            }}
            phoneName="phone"
            name="messageCode"
            rules={[
              {
                required: true,
                message: '请输入短信验证码',
              },
            ]}
            placeholder="请输入短信验证码"
            onGetCaptcha={async (phone) => {
              if (
                typeof updateRef.current?.getFieldValue('imageCode') !== 'undefined' &&
                updateRef.current?.getFieldValue('imageCode') !== ''
              ) {
                const data = await getMessageCode({
                  phone,
                  imageCode: updateRef.current?.getFieldValue('imageCode'),
                  imageCodeKey: updateRef.current.getFieldValue('imageCodeKey'),
                });
                if (data) {
                  message.success(`手机号 ${phone} 验证码发送成功!`);
                } else {
                  updateRef.current?.validateFields(['imageCode']);
                  throw new Error('图片验证码错误');
                }
              } else {
                updateRef.current?.validateFields(['imageCode']);
                throw new Error('请先输入图片验证码');
              }
            }}
          />
          <ProFormText.Password
            name="loginKey"
            fieldProps={{
              size: 'large',
            }}
            placeholder="请输入新密码"
            rules={[
              {
                required: true,
                message: '请输入密码！',
              },
            ]}
          />
        </div>
      </ModalForm>
      <Footer />
    </div>
  );
};

export default Login;
